package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.model.Position
import com.fishingwithme.android.data.model.SpotAddDTO
import com.fishingwithme.android.data.model.SpotProperty
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject

data class SpotAddUiState(
    val isLoading: Boolean = false,
    val error: String? = null,
    val props: SpotProperty = SpotProperty(),
    val currentLocation: Position? = null,
    val isSaveSuccess: Boolean = false,
    val spotName: String = "",
    val latitude: Double = 0.0,
    val longitude: Double = 0.0,
    val isFree: Boolean = false,
    val isForbidden: Boolean = false,
    val isPrivate: Boolean = true,
    val parkingEasy: Boolean = true, // 1:方便, 0:不便
    val selectedLevel: String = "",
    val selectedDistance: String = "",
    val selectedWaterType: String = "",
    val selectedSpotType: Set<String> = emptySet(),
    val selectedFishTypes: Set<String> = emptySet(),
    val description: String = "",
    val photos: List<String> = emptyList(),
    val line: List<Position> = emptyList()
)

@HiltViewModel
class SpotsViewModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(SpotAddUiState())
    val uiState: StateFlow<SpotAddUiState> = _uiState.asStateFlow()

    // Form state update functions
    fun updateSpotName(name: String) {
        _uiState.update { it.copy(spotName = name) }
    }

    fun updateLocation(latitude: Double, longitude: Double) {
        _uiState.update { it.copy(latitude = latitude, longitude = longitude) }
    }

    fun updateIsFree(isFree: Boolean) {
        _uiState.update { it.copy(isFree = isFree) }
    }

    fun updateIsForbidden(isForbidden: Boolean) {
        _uiState.update { it.copy(isForbidden = isForbidden) }
    }

    fun updateIsPrivate(isPrivate: Boolean) {
        _uiState.update { it.copy(isPrivate = isPrivate) }
    }

    fun updateParkingEasy(parkingEasy: Boolean) {
        _uiState.update { it.copy(parkingEasy = parkingEasy) }
    }

    fun updateSelectedLevel(level: String) {
        _uiState.update { it.copy(selectedLevel = level) }
    }

    fun updateSelectedDistance(distance: String) {
        _uiState.update { it.copy(selectedDistance = distance) }
    }

    fun updateSelectedWaterType(waterType: String) {
        _uiState.update { it.copy(selectedWaterType = waterType) }
    }

    fun updateSelectedSpotType(spotTypes: Set<String>) {
        _uiState.update { it.copy(selectedSpotType = spotTypes) }
    }

    fun updateSelectedFishTypes(fishTypes: Set<String>) {
        _uiState.update { it.copy(selectedFishTypes = fishTypes) }
    }

    fun updateDescription(description: String) {
        _uiState.update { it.copy(description = description) }
    }

    fun updatePhotos(photos: List<String>) {
        _uiState.update { it.copy(photos = photos) }
    }

    fun updatePoints(points: List<Position>) {
        _uiState.update { it.copy(line = points) }
    }

    fun toggleSpotType(spotType: String) {
        val currentSpotTypes = _uiState.value.selectedSpotType.toMutableSet()
        if (spotType in currentSpotTypes) {
            currentSpotTypes.remove(spotType)
        } else {
            currentSpotTypes.add(spotType)
        }
        _uiState.update { it.copy(selectedSpotType = currentSpotTypes) }
    }

    fun toggleFishType(fishType: String) {
        val currentFishTypes = _uiState.value.selectedFishTypes.toMutableSet()
        if (fishType in currentFishTypes) {
            currentFishTypes.remove(fishType)
        } else {
            currentFishTypes.add(fishType)
        }
        _uiState.update { it.copy(selectedFishTypes = currentFishTypes) }
    }

    suspend fun uploadFile(file: File): Flow<Result<String>> {
        return repository.uploadFile(file)
    }
    
    fun loadProps() {
        try {
            viewModelScope.launch {
                _uiState.update { it.copy(isLoading = true, error = null) }
                val flow: Result<SpotProperty> = repository.loadAddSpotProperties().first()
                flow.fold(
                    onSuccess = { spotProperty ->
                        _uiState.update {
                            it.copy(
                                props = spotProperty,
                                error = null,
                                isLoading = false
                            )
                        }
                    },
                    onFailure = { e ->
                        _uiState.update {
                            it.copy(
                                error = "加载失败: ${e.message ?: "未知错误"}",
                                isLoading = false
                            )
                        }
                    }
                )

            }
        } catch (e: Exception) {
            _uiState.update {
                it.copy(
                    error = "请求超时，请检查网络后重试",
                    isLoading = false
                )
            }
        }

    }

    fun saveSpot() {
        val state = _uiState.value
        // 表单校验
        if (!isFormValid()) return
        
        val dto = SpotAddDTO(
            name = state.spotName,
            circleId = 1L,
            location = Position(state.latitude, state.longitude),
            description = state.description,
            isFree = !state.isFree,
            secret = !state.isPrivate,
            isForbidden = state.isForbidden,
            parkingEasy = state.parkingEasy,
            lvl = state.selectedLevel,
            distance = state.selectedDistance,
            waterType = state.selectedWaterType,
            spotTypes = state.selectedSpotType.toList(),
            fishTypes = state.selectedFishTypes.toList(),
            pics = state.photos,
            line = state.line
        )
        
        viewModelScope.launch {
            try {
                // 设置加载状态
                _uiState.update { it.copy(isLoading = true, error = null, isSaveSuccess = false) }

                // 调用仓库保存钓点
                val result = repository.addSpot(dto).firstOrNull()

                if (result == null) {
                    _uiState.update {
                        it.copy(
                            error = "未获取到保存结果",
                            isLoading = false
                        )
                    }
                } else {
                    result.fold(
                        onSuccess = {
                            // 保存成功
                            _uiState.update {
                                it.copy(
                                    error = null,
                                    isLoading = false,
                                    isSaveSuccess = true
                                )
                            }
                        },
                        onFailure = { e ->
                            // 保存失败
                            _uiState.update {
                                it.copy(
                                    error = "保存钓点失败: ${e.message ?: "未知错误"}",
                                    isLoading = false,
                                    isSaveSuccess = false
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        error = "保存钓点时发生错误: ${e.message ?: "未知错误"}",
                        isLoading = false,
                        isSaveSuccess = false
                    )
                }
            }
        }
    }

    // 表单校验
    private fun isFormValid(): Boolean {
        val state = _uiState.value
        return state.spotName.isNotBlank()
                && state.photos.isNotEmpty()
                && state.selectedSpotType.isNotEmpty()
                && state.selectedFishTypes.isNotEmpty()
    }

    // 重置保存状态（用于需要重新保存的场景）
    fun resetSaveState() {
        _uiState.update { it.copy(isSaveSuccess = false) }
    }

    // 清除错误信息
    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
}